<template>
    <div class="owner-management">
        <!-- 搜索框 -->
        <el-card class="search-card" shadow="hover">
            <el-form :inline="true" :model="keyword" ref="searchForm" class="search-form">
                <el-form-item label="业主姓名:">
                    <el-input size="medium" clearable v-model="keyword.blur" placeholder="输入业主姓名进行搜索">
                    </el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" size="medium" @click="search" icon="el-icon-search">查询</el-button>
                    <el-button type="primary" plain size="medium" @click="resetSearchForm('searchForm')"
                        icon="el-icon-refresh">重置</el-button>
                    <el-button type="primary" plain size="medium" @click="downloadExcel"
                        icon="el-icon-download">导出</el-button>
                    <el-button type="primary" size="medium" @click="openAdd()" icon="el-icon-plus">添加业主</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 列表 -->
        <el-card class="table-card" shadow="hover">
            <el-table :data="ownerList" style="width: 100%" class="data-table">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="编号" align="center" prop="ownerId" />
                <el-table-column label="业主名称" align="center" prop="ownerName" />
                <el-table-column label="联系电话" align="center" prop="contactNumber" />
                <el-table-column label="身份证号码" align="center" prop="idNumber" />
                <el-table-column label="性别" align="center" prop="gender" />
                <el-table-column label="房屋编号" align="center" prop="houseId" />
                <el-table-column label="房屋购买时间" align="center" prop="purchaseDate" />
                <el-table-column label="车位" align="center" prop="parkingSpaceNumber" />
                <el-table-column label="车位状态" align="center" prop="useStatus" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-edit"
                            @click="handleUpdate(scope.row)">查看</el-button>
                        <el-button size="mini" type="text" icon="el-icon-delete"
                            @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 分页 -->
        <el-card class="pagination-card" shadow="hover">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :page-sizes="[5, 15, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>

        <!-- 弹框 -->
        <el-dialog :visible.sync="dialogFormVisible" :title="title" width="40%" custom-class="custom-dialog">
            <el-form :model="ownerFrom" :rules="ownerFromRules" ref="ownerFrom" label-width="120px" class="custom-form">
                <el-form-item label="业主名称" prop="ownerName">
                    <el-input v-model="ownerFrom.ownerName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="ownerFrom.gender" class="radio-group">
                        <el-radio-button label="1">男</el-radio-button>
                        <el-radio-button label="2">女</el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="联系方式" prop="contactNumber">
                    <el-input v-model="ownerFrom.contactNumber" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="身份证号码" prop="idNumber">
                    <el-input v-model="ownerFrom.idNumber" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="房屋信息" prop="houseInfo" v-if="title === '查看业主'">
                    <el-input v-model="ownerFrom.houseInfo" autocomplete="off" disabled></el-input>
                </el-form-item>
                <div v-if="title === '查看业主'">
                    <el-form-item label="房屋购买时间" prop="purchaseDate">
                        <el-date-picker v-model="ownerFrom.purchaseDate" type="date" placeholder="选择日期"
                            class="date-picker"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="车位" prop="parkingSpaceNumber">
                        <el-input v-model="ownerFrom.parkingSpaceNumber" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="车位状态" prop="useStatus">
                        <el-select v-model="ownerFrom.useStatus" placeholder="请选择车位状态" class="select-status">
                            <el-option label="可租用" value="available"></el-option>
                            <el-option label="已租用" value="rented"></el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <!-- 仅在添加业主时显示确定按钮 -->
                <el-button v-if="title === '添加业主'" type="primary" @click="addOrUpdate()">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { ownerPage, addOwner, delOwner, selectById, propertyPage, updateOwnerList } from "@/api/psm/property"
export default {
    data() {
        return {
            //分页参数
            currentPage: 1,
            total: 0,
            pageSize: 5,
            pageNum: 1,
            //列表数据
            ownerList: [],
            houseList: [],
            roomNumberList: [],
            gender: '1',
            //多选框
            measureCodes: [],
            ids: [],
            input: '',
            //搜索条件
            keyword: {
                blur: '',
            },
            //添加/修改弹框
            dialogFormVisible: false,
            //批量修改转化客户弹框
            dialogUpdateFormVisible: false,
            //弹框标题
            title: '',
            //弹框表单
            ownerFrom: {
                id: '',
                ownerName: '',
                contactNumber: '',
                houseId: '',
                roomNumber: '',
                idNumber: '',
                gender: '',


            },

            isShowPrimary: false,
            //批量修改转化客户
            batchUpdate: {
                sysZhkehu: '',
            }

        }
    },
    methods: {
        //获取展示数据
        fetchData() {
            this.getInfo();
            let params = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                ownerName: this.keyword.blur,
            }
            console.log(params)
            ownerPage(params).then(res => {
                this.total = res.data.total
                this.ownerList = res.data.list
            })
            // propertyPage().then(res => {
            //     console.log("查询信息", res)
            //     this.total = res.data.total
            //     this.houseList = res.data.list
            // })
        },
        // 模糊搜索
        search() {
            this.fetchData()
        },
        // 重置表单
        resetSearchForm(formName) {
            this.$refs[formName].resetFields();
            this.keyword = {}
            this.fetchData()
        },
        // 标签类型
        getTagType(status) {
            switch (status) {
                case 0:
                    return 'warning'; // 假设 0 表示未处理
                case 1:
                    return 'success';    // 假设 1 表示已连续
                case 2:
                    return 'info';  // 假设 2 表示已关闭
            }
        },
        // 多选框选中数据
        handleSelectionChange(selectionRowArr) {
            this.ids = [];
            console.log(selectionRowArr)
            for (let i = 0; i < selectionRowArr.length; i++) {
                this.ids.push(selectionRowArr[i].id)
            }
            // console.log("ids", this.ids)
        },
        //批量修改转化客户
        updateSysZhkehu() {
            this.batchUpdate = {}
            //获取转化客户列表
            dictList({ dictType: 'sys_zhkehu' }).then(res => {
                this.sysZhkehuList = res.data
            })
            this.dialogUpdateFormVisible = true
        },
        //提交批量修改
        updateSysZhkehuSubmit() {
            let params = {
                ids: this.ids,   // 选中的id
                sysZhkehu: this.batchUpdate.sysZhkehu,   // 转化客户
            }
            console.log("批量更新参数", params)
            updateClueStatus(params).then(res => {
                if (res.code == 200) {
                    this.$message.success('修改成功')
                } else {
                    this.$message.error('修改失败')
                }
            })
            this.dialogUpdateFormVisible = false
            this.fetchData()
        },
        //打开添加弹窗
        openAdd() {
            this.title = '添加业主'
            this.ownerFrom = {}
            this.dialogFormVisible = true
        },
        //当来源状态变化时触发
        setPrimary() {
            if (this.clueFrom.sysXslaiyuan == '0') {
                this.isShowPrimary = true;
                //获取市场活动列表
                eventsList().then(res => {
                    this.eventsList = res.data
                })
            } else {
                this.isShowPrimary = false;
            }
        },
        getInfo() {
            // 清空房屋列表
            this.houseList = [];
            selectById().then(res => {
                console.log("房屋列表", res)
                this.houseList = res.data
                console.log("房屋列表", this.houseList)
            })
        },
        downloadExcel() {
            this.$confirm('确定要导出数据吗?', '信息', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                // 方案1: 原生js方式发起导出excel请求,后端设置响应格式
                window.location.href = "http://localhost:8081/download"
                // 方案1的话后端需要设置响应格式和内容
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消导出数据！'
                })
            })
        },

        //打开修改弹窗
        handleUpdate(row) {
            this.title = '查看业主'
            this.ownerFrom = row
            this.dialogFormVisible = true


            let params = {
                id: row.id,
            }
            //通过id获取详情
            clueInfo(params).then(res => {
                this.ownerFrom = res.data
                console.log("修改数据", this.ownerFrom)
            })
            //获取跟进状态列表
            dictList({ dictType: 'sys_gjtype' }).then(res => {
                this.sysGjtypeList = res.data
            })
            //获取转化客户列表
            dictList({ dictType: 'sys_zhkehu' }).then(res => {
                this.sysZhkehuList = res.data
            })
            if (row.sysXslaiyuan == '0') {
                this.isShowPrimary = true
                //获取市场活动列表
                eventsList().then(res => {
                    this.eventsList = res.data
                })
            } else {
                this.isShowPrimary = false
            }

            this.dialogFormVisible = true
        },
        //提交编辑/添加
        addOrUpdate() {
            if (this.title == '添加业主') {
                addOwner(this.ownerFrom).then(res => {
                    this.dialogFormVisible = false;
                    if (res.code == 200) {
                        this.$message.success('添加成功');
                    } else {
                        this.$message.error('添加失败');
                    }
                }).catch(error => {
                    console.error('添加业主失败:', error);
                    this.$message.error('添加业主失败');
                });
            } else {
                updateOwnerList(this.ownerFrom).then(res => {
                    this.dialogFormVisible = false;
                    if (res.code == 200) {
                        this.$message.success('编辑成功');
                    } else {
                        this.$message.error('编辑失败');
                    }
                }).catch(error => {
                    console.error('编辑业主失败:', error);
                    this.$message.error('编辑业主失败');
                });
            }
            this.fetchData();
        },
        // 页面大小改变时触发
        handleSizeChange(val) {
            this.pageSize = val;
            this.fetchData()
        },
        // 当前页码改变时触发
        handleCurrentChange(val) {
            this.pageNum = val;
            this.fetchData()
        },
        handleDelete(row) {
            this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                console.log("删除数据", row.ownerId)
                delOwner(row.ownerId).then(res => {
                    if (res.code == 200) {
                        this.$message.success('删除成功')
                    } else {
                        this.$message.error('删除失败')
                    }
                    this.fetchData()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
    },
    created() {
        this.fetchData()
    },

}
</script>

<style>
.box-card {
    width: 100%;
    margin-top: 10px;
}

.pagination-wrapper {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中，若需要的话 */
    margin-top: 10px;
    /* Optional: 可以添加 margin 增加间距 */
}

.custom-dialog .el-dialog__header {
    background-color: #409EFF;
    padding: 15px 20px;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
}

.custom-dialog .el-dialog__title {
    color: #fff;
    font-size: 20px;
}

.custom-dialog .el-dialog__close {
    color: #fff;
}

.custom-form {
    background-color: #f5f7fa;
    padding: 20px;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
}

.custom-form .el-form-item {
    margin-bottom: 20px;
}

.custom-form .el-form-item__label {
    color: #606266;
    font-weight: bold;
}

.custom-form .el-input__inner,
.custom-form .el-select,
.custom-form .date-picker {
    width: 100%;
    border-radius: 4px;
}

.custom-form .el-input__inner:focus,
.custom-form .el-select:focus,
.custom-form .date-picker:focus {
    border-color: #409EFF;
}

.custom-form .radio-group .el-radio-button__inner {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    color: #606266;
}

.custom-form .radio-group .el-radio-button__inner:hover {
    color: #409EFF;
}

.custom-form .radio-group .el-radio-button__orig-radio:checked+.el-radio-button__inner {
    background-color: #409EFF;
    border-color: #409EFF;
    color: #fff;
}

.custom-form .select-status .el-select-dropdown__item.selected {
    color: #409EFF;
}

.dialog-footer {
    text-align: right;
    padding: 10px;
    background-color: #fff;
    border-bottom-left-radius: 5px;
    border-bottom-right-radius: 5px;
}

.dialog-footer .el-button {
    margin-left: 10px;
}

.dialog-footer .el-button--primary {
    background-color: #409EFF;
    border-color: #409EFF;
}
</style>